//
//  ProfileViewcontroller.m
//  IntroductionApp
//
//  Created by brave on 11/08/04.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ProfileViewcontroller.h"
#import "JSONKit.h"
#import "IntroductionAppAppDelegate.h"
#import "newsTableCell.h"

#pragma mark -
#pragma mark Private interface

@interface ProfileViewcontroller ()
@property (nonatomic, retain)	NSMutableArray	*visiblePopTipViews;
@end


@implementation ProfileViewcontroller

@synthesize profileView = _profileView;
@synthesize infoBtn = _infoBtn;
@synthesize NewsTable = _NewsTable;

@synthesize ApiRequest = _ApiRequest;
@synthesize NewsAry = _NewsAry;

//private
@synthesize visiblePopTipViews = _visiblePopTipViews;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [ _profileView release ];
    [ _infoBtn release ];
    [ _NewsTable release ];
    
    [ _ApiRequest release ];
    [ _NewsAry release ];
    [ _visiblePopTipViews release ];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

/* ====================================================================================== */
#pragma mark - View lifecycle
/* ====================================================================================== */

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.NewsTable.dataSource = self;
    self.NewsTable.delegate   = self;
    
    self.NewsTable.backgroundColor = [ UIColor clearColor ];
    
    if([ IntroAPPUtil isNetworkState ]){
        // news
        self.ApiRequest = [[ SAConnectedApi alloc ]init];
        self.ApiRequest.Delegate = self;
        [ self.ApiRequest getNewsAPI ];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [ super viewDidDisappear:animated ];
    
    [ self.profileView removeFromSuperview ];
}

-(void)viewDidAppear:(BOOL)animated{
    [ super viewDidAppear:animated ];
    
   // [ self displayPopover ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    _profileView = nil;
    _infoBtn     = nil;
    _NewsTable   = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


/* ====================================================================================== */
#pragma mark - Btn Action
/* ====================================================================================== */

// TODO: Animation
-(IBAction)infoBtnTouchupInside:(id)sender{
    CATransition *transition = [CATransition animation];
    [transition setDuration:0.4];
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionReveal;
    transition.subtype = kCATransitionFromRight;
    // transitioning = YES;
    transition.delegate = self;
    [self.view.layer addAnimation:transition forKey:nil];
    
    [self.view addSubview:self.profileView];
}

/* ====================================================================================== */
#pragma mark - ASIHTTP method
/* ====================================================================================== */


- (void)requestFinished:(SAConnectedApi*)object:(NSString*)request{
    
    if(object.requestType == connectTypeNews){
        // news取得
        if([ request length ] > 0){
            self.NewsAry = [request objectFromJSONString];
            
        }
        for (int i = 0; i < [ self.NewsAry count ]; i++) {
            NSDictionary *dic = [ self.NewsAry objectAtIndex:i ];
            
            NSLog(@"title = %@",[ dic objectForKey:@"title" ]);
            NSLog(@"main = %@",[ dic objectForKey:@"main" ]);
        }
        
        [ self.NewsTable reloadData ];
        
        // サウンドバージョンチェック
        [ self.ApiRequest getAppVersion ];
        
    }else if(object.requestType == connectTypeVersion){
        // ヴァージョン取得 
        NSArray *ary = [request objectFromJSONString];
        NSDictionary *verDic = [ ary lastObject ];
        
        NSString *soundStr = [ verDic objectForKey:@"music" ];
        NSString *sdkStr   = [ verDic objectForKey:@"sdk" ];
        
        [ DefaultUril setLastSoundVersion:[ soundStr intValue ] ];
        [ DefaultUril setLastSDKVersion:[ sdkStr intValue ] ];
        
        
        // サウンドバージョンの比較
        if([ DefaultUril getNowSoundVersion ] != [ DefaultUril getLastSoundVersion ]){
            [ self displayPopover ];
        }
    }
}

- (void)requestFailed:(SAConnectedApi*)object:(NSError*)error{
    NSLog(@"error = %@",[ error description ]);
}

/* ====================================================================================== */
#pragma mark - plist
/* ====================================================================================== */
-(void)readNewsPlist{
    /* plist解析 */
    self.NewsAry = [ IntroAPPUtil readPlist:NewsFile];
    
    // DEBUG
    for (int i = 0; i < [ self.NewsAry count ]; i++) {
        NSDictionary *dic = [ self.NewsAry objectAtIndex:i ];
        
        NSLog(@"title = %@",[ dic objectForKey:@"title" ]);
        NSLog(@"main = %@",[ dic objectForKey:@"main" ]);
    }
    // DEBUG END
    
    [ self.NewsTable reloadData ];
}

/* ====================================================================================== */
#pragma mark - Table Data source
/* ====================================================================================== */

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [ self.NewsAry count ];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = [self.NewsAry objectAtIndex:indexPath.row];
    NSString *title = [ dic objectForKey:@"title" ];
	NSString *news  = [ dic objectForKey:@"main" ];
    
	CGSize textBounds = CGSizeMake(310, 9999);
    
    CGSize titleSize = [title sizeWithFont:[UIFont boldSystemFontOfSize:14 ] 
                       constrainedToSize:textBounds 
						   lineBreakMode:UILineBreakModeCharacterWrap];
    
	CGSize mainSize = [news sizeWithFont:[UIFont systemFontOfSize:13] 
                       constrainedToSize:textBounds 
						   lineBreakMode:UILineBreakModeCharacterWrap];
    
	CGFloat height = titleSize.height + mainSize.height;
    
    // 最低40以上
    if(height < 40){
        height = 40;
    }
    
	return height + 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    newsTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsTableCell"];
    if (cell == nil) {
        cell = [[[newsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"newsTableCell"] autorelease];
    }
    
    NSDictionary *dic = [ self.NewsAry objectAtIndex:indexPath.row ];
    [ cell setLabelText:[ dic objectForKey:@"title" ] :[ dic objectForKey:@"main" ] ];
    
    return cell;
}


/* ====================================================================================== */
#pragma mark - popover method
/* ====================================================================================== */

- (void)dismissAllPopTipViews {
	while ([self.visiblePopTipViews count] > 0) {
		CMPopTipView *popTipView = [self.visiblePopTipViews objectAtIndex:0];
		[self.visiblePopTipViews removeObjectAtIndex:0];
		[popTipView dismissAnimated:YES];
	}
}

- (void)displayPopover{
    
	[self dismissAllPopTipViews];
	
    NSString *message = music_update;
    if (nil == message) {
        message = @"A CMPopTipView can automatically point to any view or bar button item.";
    }
    UIColor *backgroundColor = [UIColor whiteColor];
    UIColor *textColor = [UIColor blackColor];
    
    CMPopTipView *popTipView = [[[CMPopTipView alloc] initWithMessage:message] autorelease];
    popTipView.delegate = self;
    if (backgroundColor && ![backgroundColor isEqual:[NSNull null]]) {
        popTipView.backgroundColor = backgroundColor;
    }
    if (textColor && ![textColor isEqual:[NSNull null]]) {
        popTipView.textColor = textColor;
    }
    
    popTipView.animation = arc4random() % 2;
    
    // tabberから出す
    IntroductionAppAppDelegate *appDelegate = (IntroductionAppAppDelegate *)[[UIApplication sharedApplication]delegate];
    UITabBarController *tabCon = appDelegate.tabCon;
    UITabBar *tabbar = tabCon.tabBar;
    
    [popTipView presentPointingAtView:tabbar inView:self.view animated:YES ]; 
    
    [self.visiblePopTipViews addObject:popTipView];
}

/* ====================================================================================== */
#pragma mark - popover Delegate
/* ====================================================================================== */

- (void)popTipViewWasDismissedByUser:(CMPopTipView *)popTipView {
	[self.visiblePopTipViews removeObject:popTipView];
}



@end
